<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/10/26
 * Time: 13:59
 */
namespace App\Service\Api;

use App\Events\OrderFinish;
use App\Http\Model\Mysql\OrderIncomeModel;
use App\Http\Model\Mysql\OrderModel;
use App\Http\Model\Mysql\ProductModel;
use App\Http\Model\Mysql\UserModel;
use App\Http\Model\Mysql\UserBindModel;
use App\Http\Model\Mysql\ProductCommissionModel;
use App\Utils\WechatUtil;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Jobs\AutoCancelJob;

class ExtendService extends BaseService
{
    /**
     * 现存客户
     * @param int $is_stay
     * @param int $page
     * @return array
     */
    public function extendTemp(int $is_stay = 1, int $page = 1)
    {
        $user_info  =   request()->post('api_user');
        $where['share_user']    =   $user_info['user_id'];
        $where['bind_type']     =   UserBindModel::BIND_WEAK;

        /**
         * 现存客户
         */
        if ($is_stay == 1) {
            $where[]    =   ['expire_time', '>', Carbon::now()->timestamp];
        } else {
            $where[]    =   ['expire_time', '<=', Carbon::now()->timestamp];
        }

        $client_list    =   UserBindModel::query()->where($where)->offset(($page - 1) * self::PAGE_LIMIT)->limit(self::PAGE_LIMIT)->select(['id', 'share_user', 'bind_user', 'bind_type', 'bind_time', 'expire_time'])->get()->each(function (&$item) {
                                $item->bind_info    =   UserModel::where(['uid' => $item->bind_user])->select(['uid', 'nickname', 'headimg', 'unique_id', 'openid'])->first();
                                $client_order       =   OrderModel::where(['user_id' => $item->bind_user, 'is_pay' => OrderModel::IS_PAY, ['created_at', '>', $item->bind_time]])->select([DB::raw('sum(total_price) as total_price'), DB::raw('count(*) as total_order')])->first();
                                $item->total_price  =   $client_order['total_price'] ?? 0.00;
                                $item->total_order  =   $client_order['total_order'] ?? 0;
                                $item->bind_time    =   Carbon::createFromTimestamp($item->bind_time)->toDateTimeString();
                                $item->expire_time  =   Carbon::createFromTimestamp($item->expire_time)->toDateTimeString();
                                if ($item->bind_type == UserBindModel::BIND_WEAK) {
                                    $recently_time  =   OrderModel::where(['user_id' => $item->bind_user, 'is_pay' => OrderModel::IS_PAY])->orderBy('created_at', 'desc')->value('created_at');
                                    $item->recently_time=   !empty($recently_time) ? $recently_time->toDateTimeString() : '';
                                }
                            });

        return [true, $client_list->isEmpty() ? [] : $client_list->toArray()];
    }

    /**
     * 邀请人列表
     * @param int $page
     * @return array
     */
    public function extendInvite(int $page = 1)
    {
        $user_info  =   request()->post('api_user');

        $invite_list=   UserModel::where(['s_uid' => $user_info['user_id']])->orWhere(['s_uid' => $user_info['user_id']])->offset(($page - 1) * self::PAGE_LIMIT)->limit(self::PAGE_LIMIT)->select(['uid', 'nickname', 'headimg', 'unique_id', 'openid'])->orderBy('uid', 'desc')->get()->each(function (&$item) {
                            $where['user_id']   =   $item->uid;
                            $where['is_pay']    =   OrderModel::IS_PAY;
//                            $where[]            =   ['created_at', '>', $item->bind_time];
                            $client_order       =   OrderModel::where($where)->select([DB::raw('sum(total_price) as total_price'), DB::raw('count(*) as total_order')])->first();
                            $item->total_price  =   $client_order['total_price'] ?? 0.00;
                            $item->total_order  =   $client_order['total_order'] ?? 0;
                            $item->invite_price =   OrderIncomeModel::where(['uid' => $item->uid, 'reward' => OrderIncomeModel::REWARD_INVITE, 'status' => OrderIncomeModel::STATUS_DEAL])->sum('income') ?? 0.00;
                        });
        return [true, $invite_list->isEmpty() ? [] : $invite_list->toArray()];
    }

    /**
     * 推广商品列表
     * @param string $sort     排序字段
     * @param string $desc     排序方式
     * @param int $page     当前页码
     * @return array
     */
    public function extendGood(string $sort, string $desc, int $page = 1)
    {
        $good_sort  =   'p.id';
        switch ($sort) {
            case 'real_sales':
                $good_sort  =   'p.real_sales';
                break;

            case 'commission_price':
                $good_sort  =   'pc.commission_price';
                break;

            case 'sell_price':
                $good_sort  =   'p.sell_price';
                break;
        }
        $good_desc  =   $desc == 1 ? 'desc' : 'asc';
        $good_list  =   DB::table('mini_product_commission as pc')->join('mini_product as p', 'pc.product_id', '=', 'p.id')->where(['pc.is_delete' => ProductCommissionModel::NOT_DELETE, 'p.is_delete' => ProductModel::NOT_DELETE])->offset(($page - 1) * self::PAGE_LIMIT)
                        ->limit(self::PAGE_LIMIT)->select(['p.id', 'p.name', 'p.cover_pic', 'p.sell_price', 'p.real_sales', 'pc.commission_price', 'p.unique_id'])->orderBy($good_sort, $good_desc)->get()->each(function(&$item) {
                        });

        return [true, $good_list->isEmpty() ? [] : $good_list->toArray()];
    }

    /**
     * 推广商品分享
     * @param string $good_unique
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function extendShare(string $good_unique)
    {
        $user_info  =   request()->post('api_user');
        [$flag, $result]    =   WechatUtil::getUnlimitedCode(['scene' => 'share'], $user_info['user_id']);  //, 'page' => 'page/goods/detail?good_id=' . $good_unique . '&user_id=' . $user_info['unique_id']
        if ($flag) {
            return [true, [
                'user_info' =>  $user_info,
                'code_img'  =>  $result['img_path'],
            ]];
        } else {
            return [false, '二维码生成失败'];
        }
    }

}
